'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 创建组织表
    await queryInterface.createTable('organizations', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      name: {
        type: Sequelize.STRING(200),
        allowNull: false,
        comment: '组织/公司名称'
      },
      code: {
        type: Sequelize.STRING(100),
        unique: true,
        comment: '组织编码'
      },
      description: {
        type: Sequelize.TEXT,
        comment: '组织描述'
      },
      contact_info: {
        type: Sequelize.TEXT,
        comment: '联系信息'
      },
      address: {
        type: Sequelize.STRING(500),
        comment: '地址'
      },
      status: {
        type: Sequelize.INTEGER,
        defaultValue: 1,
        comment: '状态:1启用,0禁用'
      },
      created_at: {
        type: Sequelize.DATE
      },
      updated_at: {
        type: Sequelize.DATE
      }
    });

    // 创建用户组织关联表
    await queryInterface.createTable('user_organizations', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      user_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '用户ID'
      },
      organization_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '组织ID'
      },
      role: {
        type: Sequelize.STRING(50),
        comment: '在组织中的角色'
      },
      permissions: {
        type: Sequelize.TEXT,
        comment: '特殊权限'
      },
      status: {
        type: Sequelize.ENUM('active', 'inactive'),
        defaultValue: 'active',
        comment: '状态'
      },
      created_at: {
        type: Sequelize.DATE
      },
      updated_at: {
        type: Sequelize.DATE
      }
    });

    // 添加索引
    await queryInterface.addIndex('organizations', ['code']);
    await queryInterface.addIndex('user_organizations', ['user_id']);
    await queryInterface.addIndex('user_organizations', ['organization_id']);
    await queryInterface.addIndex('user_organizations', ['user_id', 'organization_id']);
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('user_organizations');
    await queryInterface.dropTable('organizations');
  }
};